package com.cyh.exp.controller;


import com.cyh.exp.mode.Result;
import com.cyh.exp.mode.ReturnCode;
import com.cyh.exp.service.DownloadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@RestController
@RequestMapping("/demo")
public class DownFileController {


    DownloadService downloadService;

    @Autowired
    private void setDownloadService(DownloadService downloadService){
        this.downloadService=downloadService;
    }

    @GetMapping("/getFileAll")
    public Result getFile(){
        return downloadService.getFileall();
    }

    @RequestMapping("/download")
    public void DownFile(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        try {
            //从网站上下载文件时，需要知道下载的是哪一个文件，因此需要获取文件名称(包括后缀)
            String logNameReq = request.getParameter("file");
            //关键点，需要获取的文件所在文件系统的目录，定位准确才可以顺利下载文件
            String filePath = "E:\\misuce_eg\\" + logNameReq;
            File file = new File(filePath);
            //创建一个输入流，将读取到的文件保存到输入流
            InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 重要，设置response的Header
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(logNameReq.getBytes()));
            response.setHeader("Content-Length", "" + file.length());
            //octet-stream是二进制流传输，当不知文件类型时都可以用此属性
            response.setContentType("blob");
            //跨域请求，*代表允许全部类型
            response.setHeader("Access-Control-Allow-Origin", "*");
            //允许请求方式
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            //用来指定本次预检请求的有效期，单位为秒，在此期间不用发出另一条预检请求
            response.setHeader("Access-Control-Max-Age", "3600");
            //请求包含的字段内容，如有多个可用哪个逗号分隔如下
            response.setHeader("Access-Control-Allow-Headers", "content-type,x-requested-with,Authorization, x-ui-request,lang");
            //访问控制允许凭据，true为允许
            response.setHeader("Access-Control-Allow-Credentials", "true");
            //创建一个输出流，用于输出文件
            OutputStream oStream = new BufferedOutputStream(response.getOutputStream());
            //写入输出文件
            oStream .write(buffer);
            oStream .flush();
            oStream .close();
            System.out.println("下载日志文件" + logNameReq +"成功");
        } catch (Exception e) {
            System.out.println("下载日志文件出错,错误原因:" + e);
        }
    }



}
